package org.jeecg.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.jeecg.common.MessageProtocol;
import org.jeecg.test.TestServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @author xiaoxiyuan
 * @description 服务端业务处理器
 * @date 2020-06-11 15:15:06
 */
@Component
@ChannelHandler.Sharable
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol>{
    @Autowired
    TestServiceImpl service;

    //记录接收的包数量
    private int count;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {

        //接收到数据，并处理
        int len = msg.getLen();
        byte[] content = msg.getContent();

        System.out.println("======服务器接收到信息如下======");
        System.out.println("长度：" + len);
        System.out.println("内容：" + new String(content, Charset.forName("utf-8")));
        System.out.println("服务器接收到消息包数量：" + (++this.count));

        //回复消息，即向客户端写数据
        String responseContent = UUID.randomUUID().toString();
        int responseLen = responseContent.getBytes("utf-8").length;
        byte[]  responseContentBytes = responseContent.getBytes("utf-8");
        //构建一个协议包
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(responseLen);
        messageProtocol.setContent(responseContentBytes);

        //将消息写回到客户端
        ctx.writeAndFlush(messageProtocol);

    }
}

